//
//  RdbGuideControllerViewController.swift
//  rdb-led-banner
//
//  Created by radiobox3 on 2025/4/18.
//

import UIKit
import SnapKit


class RdbGuideController: UIPageViewController, UIPageViewControllerDelegate {

    var currentPage: Int = 0
    
    var controllers: [UIViewController] = []

    var closeAction: (() -> Void)?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.controllers = [
            RdbGuidePlayController(type: .first),
            RdbGuidePlayController(type: .second),
            RdbGuidePlayController(type: .third),
            RdbGuidePlayController(type: .fourth)
        ]
        
        self.view.addSubview(continueButton)
        self.continueButton.snp.makeConstraints{
            $0.bottom.equalTo(-UIDevice.safeAreaBottom() - 33)
            $0.centerX.equalToSuperview()
            $0.size.equalTo(CGSize(width: UIDevice.contentWidth(), height: 54))
        }
        
        self.view.addSubview(pageControl)
        self.pageControl.snp.makeConstraints{
            $0.bottom.equalTo(continueButton.snp.top).offset(-12)
            $0.width.left.equalToSuperview()
        }
        
        self.pageControl.numberOfPages = self.controllers.count
        self.pageControl.currentPage = 0
        self.pageControl.hidesForSinglePage = true
        self.pageControl.currentPageIndicatorTintColor = UIColor("#37FF47")
        
        self.reloadCloseButtonStatus()
        
        self.setViewControllers([self.controllers.first!], direction: .forward, animated: false)
    }
    
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        if Locale.isRTL(){
            self.pageControl.semanticContentAttribute = .forceRightToLeft
            self.continueButton.semanticContentAttribute = .forceLeftToRight
        }else{
            self.pageControl.semanticContentAttribute = .forceLeftToRight
            self.continueButton.semanticContentAttribute = .forceLeftToRight
        }
    }
    
    private lazy var pageControl: UIPageControl = {
        let pageControl = UIPageControl()
        pageControl.isUserInteractionEnabled = false
        return pageControl
    }()
    
    private lazy var continueButton: UIButton = RdbViewUtils.shared.createCircleButton(
        fontSize: 22.0,
        title: "CONTINUE",
        cornerRadius: 27,
        backgroundColor: "#5210E1",
        target: self,
        action: #selector(continueButtonAction)
    )
    
    @objc func continueButtonAction(){
        self.currentPage += 1
        if self.currentPage < self.controllers.count {
            self.pageControl.currentPage = self.currentPage
            self.setViewControllers([self.controllers[self.currentPage]], direction: Locale.isRTL() ? .reverse : .forward, animated: true)
            self.reloadCloseButtonStatus()
        }
        if self.currentPage >= self.controllers.count {
            print("订阅...")
        }
    }
    
    
    
    func reloadCloseButtonStatus() {
        self.hiddenCloseButton()
        if self.currentPage >= self.controllers.count - 1 {
            self.showCloseButton()
        } else {
            self.hiddenCloseButton()
        }
    }
    
    func showCloseButton(){
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0){
            if #available(iOS 16.0, *){
                self.closeButtonItem.isHidden = false
            }else{
                self.navigationItem.rightBarButtonItem = self.closeButtonItem
            }
        }
    }

    func hiddenCloseButton() {
        if #available(iOS 16.0, *) {
            self.navigationItem.rightBarButtonItem = self.closeButtonItem
            self.closeButtonItem.isHidden = true
        } else {
            self.navigationItem.rightBarButtonItem = nil
        }
    }
    
    private lazy var closeButtonItem: UIBarButtonItem = {
        let closeButtonItem = UIBarButtonItem(image: UIImage(named: "guide_close")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(closeButtonAction))
        return closeButtonItem
    }()
    
    @objc func closeButtonAction(){
        self.dismissPage()
    }
    
    private func dismissPage(){
        self.closeAction?()
    }
    
    func pageViewControllerSupportedInterfaceOrientations(_ pageViewController: UIPageViewController) -> UIInterfaceOrientationMask {
        return .portrait
    }
    func pageViewControllerPreferredInterfaceOrientationForPresentation(_ pageViewController: UIPageViewController) -> UIInterfaceOrientation {
        return .portrait
    }
    
    override init(transitionStyle style: UIPageViewController.TransitionStyle, navigationOrientation: UIPageViewController.NavigationOrientation, options: [UIPageViewController.OptionsKey : Any]? = nil) {
        super.init(transitionStyle: style, navigationOrientation: navigationOrientation, options: options)
        self.modalPresentationStyle = .fullScreen
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
